<template>
	<view class="container">
		<!-- 模块 start -->
		<view class="section">
			<!--			<view class="section-title" style="margin: 10px;">基 本信息</view>-->
			<view class="section-item">
				<view class="item flex space-between">
					<view class="key"> 头像 </view>
					<view class="value flex flex-justify-end">
						<button class="avatar " open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
							<image :src="avatar_u"></image>
							<!-- <image :src="mediaUrl+avatar"></image> -->
						</button>
					</view>
				</view>
				<view class="item flex space-between">
					<view class="key"> 昵称 </view>
					<input type="nickname" maxlength="8" v-model="nickname" class="value" @change="getUserNickName"
						placeholder="请输入昵称" />
				</view>
				<!-- <view class="item flex space-between">
					<u-picker :show="typeshow" :columns="columns" @confirm="confirm" @cancel="typecancel" ></u-picker>
				</view> -->
				<!-- <view class="item flex space-between">
					<text class="key">个人简介</text>
					<textarea  class="value" :disable-default-padding="true" maxlength="30" :auto-height="true" @input="getprofile" :value="profile" placeholder="真诚的介绍可以让别人对你更信任"></textarea>
				</view> -->
				<view class="item flex space-between">
					<text class="key">联系方式</text>
					<input class="value" disabled @click="getphone" :value="userInfo.username" />
				</view>

			</view>
		</view>
		<!-- 模块 end -->

		<!-- 底部按钮 start -->
		<view class="btn-box w100 fixed">
			<u-button class="btn btn-save" color="#7780C8" @click="btnmodify" :throttle-time="throttleTime"
				:loading="loading">保存</u-button>
		</view>
		<!-- 底部按钮 end -->

	</view>
</template>

<script>
	const COS = require('cos-wx-sdk-v5');

	export default {
		data() {
			return {
				mediaUrl: uni.$http.mediaUrl,
				avatar: null,
				avatar_u: null,
				nickname: '',
				openid: uni.getStorageSync('openid'),
				loading: false,
				throttleTime: 1000,
				userInfo: uni.getStorageSync('userInfo'),
				typeshow: false,
				columns: [
					['男', '女', '其他']
				],

				profile: '',
			};
		},
		onLoad() {
			self = this
		},
		onShow() {
			// self = this
			this.getMyInfo()
		},
		methods: {
			getphone() {
				uni.showModal({
					title: '温馨提示',
					content: '亲爱的用户，为保护您的账户安全，联系方式不可修改哦！',
					showCancel: false
				})
			},
			async getMyInfo() {
				console.log('getMyInfo' + this.userInfo.username)
				const userInfo = {
					username: this.userInfo.username,
					openid: this.openid,

				}
				const {
					data: res
				} = await uni.$http.post('getMyInfo/', userInfo)
				if (res.code == 200) {
					// console.log(res)
					// this.nickname = unescape(res.data.nickname)
					this.nickname = res.data.nickname
					this.avatar_u = res.data.avatar
					// this.avatar_u = this.mediaUrl + this.avatar
					this.profile = res.data.profile
				} else {
					// uni.showToast({ icon:'error', title: res.msg })
				}
			},
			uploadFilePromise(url) {
				// console.log(url)
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: uni.$http.baseUrl + 'avatarUpload/', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'avatarfile',
						formData: {
							openid: this.openid,

						},
						success: (res) => {
							var meta = JSON.parse(res.data);
							// console.log(meta.url)
							// setTimeout(() => {
							resolve(meta.data)
							// }, 1000)
						},
						fail: (res) => {
							console.log(res)
						}
					});
				})
			},
			getUserNickName(e) {
				console.log(e)
				const getNickName = e.detail.value
				if (getNickName) {
					this.nickname = getNickName
					// console.log(this.nickName)
				}
			},
			async onChooseAvatar(e) {
				const {
					avatarUrl: filePath
				} = e.detail
				const cos = new COS({
					SecretId: 'AKIDDKRWo9cAkIvz0ptpZFl4sjUD55xdJrW7',
					SecretKey: 'd5LRK1WotmU0JiDYhePyKfp5KPL9mJhu',
				});
				uni.getFileSystemManager().readFile({
					filePath: filePath,
					success: (res) => {
						cos.putObject({
							Bucket: 'lyg-1254016590', // 存储桶名称
							Region: 'ap-nanjing', // 区域
							Key: '/avatar/' + Date.now() + '-' + Math.random().toString(36)
								.substr(2, 8), // 文件路径及名称
							Body: res.data,
							onProgress: (progressData) => {
								console.log('进度:', JSON.stringify(progressData));
							}
						}, (err, data) => {
							if (err) {
								console.error('上传失败:', err);
							} else {
								console.log('上传成功:', data);
								this.avatar_u = 'https://' + data.Location
							}
						});
					},
					fail: (error) => {
						console.error('读取文件失败:', error);
					}
				});
			},
			getprofile(e) {

				this.profile = e.detail.value.replace(/[^\u4E00-\u9FA5|\d|\a-zA-Z|\r\n\s,.?!，。？！…—&$=()-+/*{}[\]]/g, '');
				if (this.profile != e.detail.value) {
					console.log('抱歉不可包含特殊字符')
					uni.showToast({
						icon: 'none',
						title: '抱歉不可包含特殊字符',
						duration: 2000
					})

				}

			},
			async btnmodify() {
				// 不需要判断有没有修改,直接提交就行
				//判断是否有修改头像
				// if (this.avatar_u.indexOf("media") < 0) {
				// 	await this.uploadFilePromise(this.avatar_u)
				// }
				//判断昵称是否为空
				if (!this.nickname) {
					uni.showToast({
						icon: 'error',
						title: '请输入昵称',
						duration: 1000
					})
					return;
				}
				console.log(this.nickname)
				const userInfo = {
					username: this.userInfo.username,
					// nickname:escape(this.nickname),
					avatar: this.avatar_u,
					nickname: this.nickname,
					profile: this.profile,
				}
				console.log('userInfo--', userInfo)
				this.loading = true;
				const {
					data: res
				} = await uni.$http.post('updateMyInfo/', userInfo)
				if (res.code == 200) {
					this.loading = false;
					this.userInfo.avatar = this.avatar_u
					this.userInfo.nickname = this.nickname
					// console.log(this.userInfo)
					uni.setStorageSync('userInfo', this.userInfo)
					uni.showToast({
						icon: 'success',
						title: '保存成功',
						duration: 1000
					})
					setTimeout(function() {
						uni.reLaunch({
							url: '/pages/mine/mine'
						})
					}, 1000);
				} else {
					uni.showToast({
						icon: 'error',
						title: res.msg
					})
				}
			},


		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}

	.item {
		border-bottom: 1px solid #EFEFEF;
		min-height: 100rpx;

		.key {
			color: #262626;
		}

		.value {
			color: #8E8E8E !important;
		}
	}

	button {
		padding: 0;
	}

	/* 底部按钮 */
	.btn-box {

		//background-color: #fff;
		//box-shadow: 0 0 12rpx rgba(132, 129, 200, .3);
		.btn {
			// border-radius: 12rpx;
		}
	}
</style>